{{ template "page/head_start" .}}
<style>
  body {
    background-color: #f5f7fa;
  }

  .save-bar {
    position: sticky;
    top: 0;
    z-index: 100;
    background: white;
    padding: 1rem 0;
    margin-bottom: 1.5rem;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
  }

  .nav-tabs {
    border-bottom: 2px solid #dee2e6;
  }

  .nav-tabs .nav-link {
    color: #6c757d;
    font-weight: 600;
    border: none;
    border-bottom: 3px solid transparent;
    padding: 1rem 1.5rem;
    transition: all 0.3s ease;
  }

  .nav-tabs .nav-link:hover {
    color: #667eea;
    background: rgba(102, 126, 234, 0.05);
  }

  .nav-tabs .nav-link.active {
    color: #667eea;
    background: transparent;
    border-bottom-color: #667eea;
  }

  .config-card {
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 1.5rem;
  }

  .config-label {
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 0.5rem;
  }

  .config-description {
    font-size: 0.875rem;
    color: #7f8c8d;
    margin-bottom: 0.75rem;
  }

  .json-editor {
    width: 100%;
    min-height: 500px;
    font-family: 'Courier New', monospace;
    font-size: 0.9rem;
    padding: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    background: #f8f9fa;
  }

  .btn-save {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-save:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    color: white;
  }

  .btn-save:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .btn-restart {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-restart:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);
    color: white;
  }

  .btn-restart:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .alert-security {
    background: linear-gradient(135deg, #ff9100 0%, #ff5722 100%);
    color: white;
    border: none;
    border-radius: 10px;
    animation: pulse-warning 3s ease-in-out infinite;
  }

  @keyframes pulse-warning {
    0%, 100% {
      box-shadow: 0 0 0 0 rgba(255, 145, 0, 0.5);
    }
    50% {
      box-shadow: 0 0 0 6px rgba(255, 145, 0, 0);
    }
  }

  .form-switch .form-check-input {
    width: 3rem;
    height: 1.5rem;
    cursor: pointer;
  }

  .form-switch .form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
  }

  @media (max-width: 768px) {
    .nav-tabs .nav-link {
      padding: 0.75rem;
      font-size: 0.9rem;
    }
  }

  .error-message {
    background: #ffe6e6;
    border: 1px solid #ffcccc;
    color: #c62828;
    padding: 0.75rem;
    border-radius: 6px;
    margin-top: 0.5rem;
    font-family: monospace;
    font-size: 0.85rem;
  }
</style>
{{ template "page/head_end" .}}

{{ template "page/body_start" .}}
{{ template "component/sidebar" . }}

<div class="main-content">
  <!-- Top Navbar -->
  <nav class="navbar-top">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h4 class="mb-0"><i class="bi bi-gear-wide-connected me-2"></i>Xray {{ i18n "menu.xray" }}</h4>
        <small class="text-muted">{{ i18n "pages.xray.manage" }}</small>
      </div>
    </div>
  </nav>

  <div class="container-fluid px-4">
    <!-- Loading State -->
    <div id="loadingState" class="text-center py-5">
      <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;"></div>
      <p class="mt-3 text-muted">{{ i18n "loading" }}...</p>
    </div>

    <!-- Main Content -->
    <div id="mainContent" style="display: none;">
      <!-- Security Alert -->
      <div id="securityAlert" class="mb-3" style="display: none;">
        <div class="alert alert-security">
          <h5 class="mb-0"><i class="bi bi-exclamation-triangle-fill me-2"></i>{{ i18n "secAlertTitle" }}: {{ i18n "secAlertSSL" }}</h5>
        </div>
      </div>

      <!-- Save Bar -->
      <div class="save-bar">
        <div class="d-flex justify-content-between align-items-center flex-wrap px-3">
          <div class="d-flex gap-2 mb-2 mb-md-0">
            <button class="btn btn-save" id="saveBtn" disabled>
              <i class="bi bi-check-circle me-1"></i> {{ i18n "pages.xray.save" }}
            </button>
            <button class="btn btn-restart" id="restartBtn" disabled>
              <i class="bi bi-arrow-clockwise me-1"></i> {{ i18n "pages.xray.restart" }}
            </button>
          </div>
          <div class="alert alert-warning mb-0" style="padding: 0.5rem 1rem;">
            <i class="bi bi-info-circle me-1"></i> {{ i18n "pages.settings.infoDesc" }}
          </div>
        </div>
        <div id="errorMessage" class="error-message mx-3" style="display: none;"></div>
      </div>

      <!-- Tabs -->
      <ul class="nav nav-tabs mb-4" id="xrayTabs" role="tablist">
        <li class="nav-item" role="presentation">
          <button class="nav-link active" id="basics-tab" data-bs-toggle="tab" data-bs-target="#basics" type="button">
            <i class="bi bi-gear me-1"></i> {{ i18n "pages.xray.basicTemplate" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="routing-tab" data-bs-toggle="tab" data-bs-target="#routing" type="button">
            <i class="bi bi-shuffle me-1"></i> {{ i18n "pages.xray.Routings" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="outbounds-tab" data-bs-toggle="tab" data-bs-target="#outbounds" type="button">
            <i class="bi bi-box-arrow-up me-1"></i> {{ i18n "pages.xray.Outbounds" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="dns-tab" data-bs-toggle="tab" data-bs-target="#dns" type="button">
            <i class="bi bi-hdd-network me-1"></i> DNS
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="advanced-tab" data-bs-toggle="tab" data-bs-target="#advanced" type="button">
            <i class="bi bi-code-square me-1"></i> {{ i18n "pages.xray.advancedTemplate" }}
          </button>
        </li>
      </ul>

      <!-- Tab Content -->
      <div class="tab-content" id="xrayTabContent">
        <!-- Basics Tab -->
        <div class="tab-pane fade show active" id="basics" role="tabpanel">
          <div class="config-card">
            <h5 class="mb-3"><i class="bi bi-sliders me-2"></i>{{ i18n "pages.xray.generalConfigs" }}</h5>

            <div class="mb-3">
              <div class="config-label">{{ i18n "pages.xray.logLevel" }}</div>
              <select class="form-select" id="logLevel">
                <option value="none">None</option>
                <option value="debug">Debug</option>
                <option value="info">Info</option>
                <option value="warning">Warning</option>
                <option value="error">Error</option>
              </select>
            </div>

            <div class="mb-3">
              <div class="config-label">{{ i18n "pages.xray.accessLog" }}</div>
              <input type="text" class="form-control" id="accessLog" placeholder="./access.log">
            </div>

            <div class="mb-3">
              <div class="config-label">{{ i18n "pages.xray.errorLog" }}</div>
              <input type="text" class="form-control" id="errorLog" placeholder="./error.log">
            </div>

            <div class="mb-3">
              <div class="config-label">{{ i18n "pages.xray.routing.domainStrategy" }}</div>
              <select class="form-select" id="routingStrategy">
                <option value="AsIs">AsIs</option>
                <option value="IPIfNonMatch">IPIfNonMatch</option>
                <option value="IPOnDemand">IPOnDemand</option>
              </select>
            </div>

            <div class="mb-3">
              <div class="config-label">DNS {{ i18n "pages.settings.enable" }}</div>
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="enableDNS">
              </div>
            </div>
          </div>
        </div>

        <!-- Routing Tab -->
        <div class="tab-pane fade" id="routing" role="tabpanel">
          <div class="config-card">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <h5 class="mb-0"><i class="bi bi-shuffle me-2"></i>{{ i18n "pages.xray.rules.title" }}</h5>
              <button class="btn btn-primary btn-sm" id="addRuleBtn">
                <i class="bi bi-plus-circle me-1"></i> {{ i18n "pages.xray.rules.add" }}
              </button>
            </div>

            <div class="table-responsive">
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th width="10%">#</th>
                    <th width="30%">{{ i18n "pages.xray.rules.type" }}</th>
                    <th width="30%">{{ i18n "pages.xray.rules.outbound" }}</th>
                    <th width="30%">{{ i18n "pages.xray.rules.actions" }}</th>
                  </tr>
                </thead>
                <tbody id="routingRulesTable">
                  <tr>
                    <td colspan="4" class="text-center text-muted">{{ i18n "pages.inbounds.noData" }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Outbounds Tab -->
        <div class="tab-pane fade" id="outbounds" role="tabpanel">
          <div class="config-card">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <h5 class="mb-0"><i class="bi bi-box-arrow-up me-2"></i>{{ i18n "pages.xray.Outbounds" }}</h5>
              <button class="btn btn-primary btn-sm" id="addOutboundBtn">
                <i class="bi bi-plus-circle me-1"></i> {{ i18n "pages.xray.outbound.addOutbound" }}
              </button>
            </div>

            <div class="table-responsive">
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th width="10%">#</th>
                    <th width="20%">{{ i18n "pages.xray.outbound.tag" }}</th>
                    <th width="20%">{{ i18n "protocol" }}</th>
                    <th width="30%">{{ i18n "pages.xray.outbound.address" }}</th>
                    <th width="20%">{{ i18n "pages.xray.rules.actions" }}</th>
                  </tr>
                </thead>
                <tbody id="outboundsTable">
                  <tr>
                    <td colspan="5" class="text-center text-muted">{{ i18n "pages.inbounds.noData" }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- DNS Tab -->
        <div class="tab-pane fade" id="dns" role="tabpanel">
          <div class="config-card">
            <h5 class="mb-3"><i class="bi bi-hdd-network me-2"></i>DNS {{ i18n "pages.xray.generalConfigs" }}</h5>

            <div class="mb-3">
              <div class="config-label">DNS {{ i18n "pages.settings.enable" }}</div>
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="dnsEnable">
              </div>
            </div>

            <div id="dnsConfig" style="display: none;">
              <div class="mb-3">
                <div class="config-label">Query Strategy</div>
                <select class="form-select" id="dnsStrategy">
                  <option value="UseIP">UseIP</option>
                  <option value="UseIPv4">UseIPv4</option>
                  <option value="UseIPv6">UseIPv6</option>
                </select>
              </div>

              <div class="mb-3">
                <div class="config-label">DNS Tag</div>
                <input type="text" class="form-control" id="dnsTag" value="dns_inbound">
              </div>

              <div class="mb-3">
                <div class="config-label">DNS Servers</div>
                <div class="config-description">{{ i18n "pages.xray.dns.serversDesc" }}</div>
                <textarea class="form-control" id="dnsServers" rows="5" placeholder='["8.8.8.8", "1.1.1.1"]'></textarea>
              </div>
            </div>
          </div>
        </div>

        <!-- Advanced Tab -->
        <div class="tab-pane fade" id="advanced" role="tabpanel">
          <div class="config-card">
            <h5 class="mb-3"><i class="bi bi-code-square me-2"></i>{{ i18n "pages.xray.advancedTemplate" }}</h5>
            <div class="config-description">
              {{ i18n "pages.xray.advancedTemplateDesc" }}
            </div>
            <textarea class="json-editor" id="jsonEditor"></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

{{template "page/body_scripts" .}}
<script>
let oldConfig = '';
let currentConfig = {};

$(document).ready(function() {
  loadXrayConfig();

  $('#saveBtn').on('click', saveConfig);
  $('#restartBtn').on('click', restartXray);

  // Tab switching
  $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
    if (e.target.id === 'advanced-tab') {
      $('#jsonEditor').val(JSON.stringify(currentConfig, null, 2));
    }
  });

  // JSON editor changes
  $('#jsonEditor').on('input', function() {
    try {
      const parsed = JSON.parse($(this).val());
      currentConfig = parsed;
      $('#errorMessage').hide();
    } catch (e) {
      $('#errorMessage').text('Invalid JSON: ' + e.message).show();
    }
  });

  // DNS enable toggle
  $('#dnsEnable, #enableDNS').on('change', function() {
    if ($(this).is(':checked')) {
      $('#dnsConfig').show();
      if (!currentConfig.dns) {
        currentConfig.dns = {
          servers: [],
          queryStrategy: 'UseIP',
          tag: 'dns_inbound'
        };
      }
    } else {
      $('#dnsConfig').hide();
      delete currentConfig.dns;
      delete currentConfig.fakedns;
    }
    markAsModified();
  });

  // Watch for changes
  setInterval(checkForChanges, 1000);
  $('input, select, textarea').on('input change', markAsModified);
});

function loadXrayConfig() {
  $('#loadingState').show();
  $('#mainContent').hide();

  axios.post('/panel/xray/')
    .then(response => {
      if (response.data.success) {
        const result = JSON.parse(response.data.obj);
        const config = result.xraySetting;

        oldConfig = JSON.stringify(config);
        currentConfig = JSON.parse(JSON.stringify(config));

        populateConfig(config);
        renderRoutingRules(config);
        renderOutbounds(config);

        // Check SSL
        if (window.location.protocol !== 'https:') {
          $('#securityAlert').show();
        }

        $('#loadingState').hide();
        $('#mainContent').fadeIn();
      }
    })
    .catch(error => {
      console.error('Failed to load Xray config:', error);
      $('#loadingState').hide();
    });
}

function populateConfig(config) {
  // Basics
  $('#logLevel').val(config.log?.loglevel || 'warning');
  $('#accessLog').val(config.log?.access || '');
  $('#errorLog').val(config.log?.error || '');
  $('#routingStrategy').val(config.routing?.domainStrategy || 'AsIs');

  // DNS
  const dnsEnabled = config.dns != null;
  $('#dnsEnable, #enableDNS').prop('checked', dnsEnabled);

  if (dnsEnabled) {
    $('#dnsConfig').show();
    $('#dnsStrategy').val(config.dns.queryStrategy || 'UseIP');
    $('#dnsTag').val(config.dns.tag || 'dns_inbound');
    $('#dnsServers').val(JSON.stringify(config.dns.servers || [], null, 2));
  }

  // Advanced
  $('#jsonEditor').val(JSON.stringify(config, null, 2));
}

function gatherConfig() {
  // Update from basics tab
  if (!currentConfig.log) currentConfig.log = {};
  currentConfig.log.loglevel = $('#logLevel').val();
  currentConfig.log.access = $('#accessLog').val() || undefined;
  currentConfig.log.error = $('#errorLog').val() || undefined;

  if (!currentConfig.routing) currentConfig.routing = { rules: [] };
  currentConfig.routing.domainStrategy = $('#routingStrategy').val();

  // DNS
  if ($('#dnsEnable').is(':checked')) {
    if (!currentConfig.dns) currentConfig.dns = {};
    currentConfig.dns.queryStrategy = $('#dnsStrategy').val();
    currentConfig.dns.tag = $('#dnsTag').val();

    try {
      currentConfig.dns.servers = JSON.parse($('#dnsServers').val() || '[]');
    } catch (e) {
      console.error('Invalid DNS servers JSON:', e);
    }
  }

  return currentConfig;
}

function markAsModified() {
  currentConfig = gatherConfig();
}

function checkForChanges() {
  const current = JSON.stringify(currentConfig);
  const hasChanges = oldConfig !== current;

  $('#saveBtn').prop('disabled', !hasChanges);
  $('#restartBtn').prop('disabled', hasChanges);
}

function saveConfig() {
  const config = gatherConfig();

  showLoading();
  axios.post('/panel/xray/update', { xraySetting: JSON.stringify(config, null, 2) })
    .then(response => {
      hideLoading();
      if (response.data.success) {
        showNotification('{{ i18n "success" }}', 'success');
        oldConfig = JSON.stringify(config);
        currentConfig = JSON.parse(JSON.stringify(config));
      }
    })
    .catch(error => {
      hideLoading();
      console.error('Failed to save config:', error);
    });
}

function restartXray() {
  if (!confirm('{{ i18n "pages.xray.restartXrayConfirm" }}')) return;

  showLoading();
  axios.post('/server/restartXrayService')
    .then(response => {
      hideLoading();
      if (response.data.success) {
        showNotification('{{ i18n "pages.xray.restartXraySuccess" }}', 'success');

        // Check for errors
        setTimeout(() => {
          axios.get('/panel/xray/getXrayResult')
            .then(res => {
              if (res.data.success && res.data.obj && res.data.obj.length > 1) {
                $('#errorMessage').text(res.data.obj).show();
              }
            });
        }, 1000);
      }
    })
    .catch(error => {
      hideLoading();
      console.error('Failed to restart Xray:', error);
    });
}

function renderRoutingRules(config) {
  const tbody = $('#routingRulesTable');
  tbody.empty();

  const rules = config.routing?.rules || [];

  if (rules.length === 0) {
    tbody.append('<tr><td colspan="4" class="text-center text-muted">{{ i18n "pages.inbounds.noData" }}</td></tr>');
    return;
  }

  rules.forEach((rule, index) => {
    const type = rule.type || 'field';
    const outbound = rule.outboundTag || rule.balancerTag || '-';

    const row = `
      <tr>
        <td>${index + 1}</td>
        <td>${type}</td>
        <td><code>${outbound}</code></td>
        <td>
          <button class="btn btn-sm btn-primary" onclick="editRule(${index})">
            <i class="bi bi-pencil"></i>
          </button>
          <button class="btn btn-sm btn-danger" onclick="deleteRule(${index})">
            <i class="bi bi-trash"></i>
          </button>
        </td>
      </tr>
    `;
    tbody.append(row);
  });
}

function renderOutbounds(config) {
  const tbody = $('#outboundsTable');
  tbody.empty();

  const outbounds = config.outbounds || [];

  if (outbounds.length === 0) {
    tbody.append('<tr><td colspan="5" class="text-center text-muted">{{ i18n "pages.inbounds.noData" }}</td></tr>');
    return;
  }

  outbounds.forEach((outbound, index) => {
    const tag = outbound.tag || '-';
    const protocol = outbound.protocol || '-';
    const address = getOutboundAddress(outbound);

    const row = `
      <tr>
        <td>${index + 1}</td>
        <td><strong>${tag}</strong></td>
        <td><span class="badge bg-primary">${protocol}</span></td>
        <td><small>${address}</small></td>
        <td>
          <button class="btn btn-sm btn-primary" onclick="editOutbound(${index})">
            <i class="bi bi-pencil"></i>
          </button>
          <button class="btn btn-sm btn-danger" onclick="deleteOutbound(${index})">
            <i class="bi bi-trash"></i>
          </button>
        </td>
      </tr>
    `;
    tbody.append(row);
  });
}

function getOutboundAddress(outbound) {
  switch (outbound.protocol) {
    case 'vmess':
    case 'vless':
      if (outbound.settings?.vnext) {
        return outbound.settings.vnext.map(v => `${v.address}:${v.port}`).join(', ');
      }
      break;
    case 'shadowsocks':
    case 'trojan':
    case 'http':
    case 'socks':
      if (outbound.settings?.servers) {
        return outbound.settings.servers.map(s => `${s.address}:${s.port}`).join(', ');
      }
      break;
    case 'freedom':
      return 'Direct';
    case 'blackhole':
      return 'Blocked';
  }
  return '-';
}

function editRule(index) {
  showNotification('{{ i18n "pages.xray.rules.editNotImplemented" }}', 'info');
}

function deleteRule(index) {
  if (!confirm('{{ i18n "pages.xray.rules.deleteConfirm" }}')) return;

  currentConfig.routing.rules.splice(index, 1);
  renderRoutingRules(currentConfig);
  markAsModified();
}

function editOutbound(index) {
  showNotification('{{ i18n "pages.xray.outbound.editNotImplemented" }}', 'info');
}

function deleteOutbound(index) {
  if (!confirm('{{ i18n "pages.xray.outbound.deleteConfirm" }}')) return;

  currentConfig.outbounds.splice(index, 1);
  renderOutbounds(currentConfig);
  markAsModified();
}
</script>
{{ template "page/body_end" .}}
